﻿using System;
using System.Linq;
using System.Reflection;
using Microsoft.EntityFrameworkCore;

namespace Competition.Repository
{
    public class RepositoryFactory
    {
        /// <summary>
        /// 工厂创建仓储
        /// </summary>
        /// <typeparam name="T">需要创建的类型</typeparam>
        /// <param name="dbContext">数据访问上下文</param>
        /// <returns></returns>
        public static object CreateObj<T>(DbContext dbContext) where T : class
        {
            Type type = new System.Diagnostics.StackTrace().GetFrame(0).GetMethod().DeclaringType;//当前类型
            Assembly assembyle = Assembly.GetAssembly(type);  //当前类型所在的类库
            var typeList = assembyle.GetTypes().Where(t => t.Namespace == type.Namespace);  //查找该命名空间下的所有类型
            type = typeList.FirstOrDefault(t => t.Name == typeof(T).Name + "Repository");  //查找需要实例化的类型
            object[] parameters = new object[1];
            parameters[0] = dbContext;  //构建构造参数
            return Activator.CreateInstance(type, parameters);  //实例化对象
        }
    }
}